package com.mz361.component.jwt.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.mz361.common.exception.ResultException;
import com.mz361.common.utils.RedisUtil;
import com.mz361.common.utils.StringUtil;
import com.mz361.component.jwt.annotation.IgnorePermissions;
import com.mz361.component.jwt.config.properties.JwtProjectProperties;
import com.mz361.component.jwt.enums.JwtResultEnums;
import com.mz361.component.jwt.utlis.JwtUtil;
import com.mz361.modules.system.domain.CSource;
import com.mz361.modules.system.service.CSourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * jwt权限拦截器
 *
 * @ author niceale
 * @ date 2019/4/12
 */
@Component
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    CSourceService cSourceService;

    @Autowired
    private JwtProjectProperties properties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        request.setAttribute("LOG_SEND_TIME", System.currentTimeMillis());
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 判断请求映射的方式是否忽略权限验证
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(IgnorePermissions.class)) {
            return true;
        }
        String token = request.getHeader("token");
        String key = request.getHeader("key");
        String timestamp = request.getHeader("timestamp");
        // 验证token数据是否正确
        try {
            if ("MANZHIKEY".equals(key)) {
                JwtUtil.verifyToken(token, properties.getSecret());
            } else {
                String secret = redisUtil.hGet("SOURCE:SECRET", key);
                //如果缓存中没有渠道KEY的信息则查询数据库
                if (StringUtil.isEmpty(secret)) {
                    CSource cSource = cSourceService.getBySourceKey(key);
                    if (null != cSource) {
                        secret = cSource.getSecretKey();
                        redisUtil.hSet("SOURCE:SECRET", key, secret);
                    }
                }
                JwtUtil.verifyApiToken(token, key, timestamp, secret);

            }
        } catch (TokenExpiredException e) {
            throw new ResultException(JwtResultEnums.TOKEN_EXPIRED);
        } catch (JWTVerificationException e) {
            throw new ResultException(JwtResultEnums.TOKEN_ERROR);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
